package com.crm.system.service.impl.csd.customerManager;

import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.csd.CustomerContractEnum;
import com.crm.common.model.Enum.csd.WorkLogEnum;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.DateUtil;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.csd.customerManager.CustomerServiceWorkLog;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.orderManager.CustomerProductOrder;
import com.crm.model.entity.returnMoney.ReturnMoney;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.csd.customerManager.CustomerContractUpdateQO;
import com.crm.model.vo.csd.customerManager.ContractAndOrderVO;
import com.crm.model.vo.csd.customerManager.ContractDetailVO;
import com.crm.model.vo.csd.customerManager.CustomerDetailVO;
import com.crm.model.vo.customerContractManager.CustomerContractVO;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.csd.customerManager.ContractAndOrderDbService;
import com.crm.service.csd.customerManager.CustomerDbService;
import com.crm.service.orderManager.CustomerProductOrderDbService;
import com.crm.service.returnMoney.ReturnMoneyDbservice;
import com.crm.system.service.csd.customerManager.ContractAndOrderService;
import com.crm.system.service.csd.customerManager.CustomerServiceWorkLogService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yincuimei
 * @Date 2021/8/26 16:27
 * (客服部)合同&订单
 */
@Service
public class ContractAndOrderServiceImpl implements ContractAndOrderService {
    @Autowired
    private ContractAndOrderDbService contractAndOrderDbService;

    //合同
    @Autowired
    private CustomerContractDbService customerContractDbService;

    //订单
    @Autowired
    private CustomerProductOrderDbService customerProductOrderDbService;

    @Autowired
    private CustomerServiceWorkLogService workLogService;

    @Autowired
    private CustomerDbService customerDbService;

    @Autowired
    private ReturnMoneyDbservice returnMoneyDbservice;

    /**
     * 合同&订单列表
     * 业务描述：
     *       查询未删除的合同信息及订单编号;
     *       可按审核人、当前状态、合同开始日期(前端列名是有效起止即合同开始和结束日期)排序
     *       默认按合同开始日期排序(倒序)
     * @param customerId         客户ID
     * @param queryType          查询类型-contract:合同;order:订单
     * @param pageIndex/pageSize 页码/分页大小
     * @param sortName           排序字段
     * @param sortOrder          排序规则
     * @author yincuimei
     * @return
     */
    @Override
    public DhPageInfo<ContractAndOrderVO> selectContractAndOrderVOList(String customerId,String queryType,Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //排序
        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "contractStartAndEnd": {//前端(有效起止列)
                    order.append("t.contract_start_date ").append(sortOrder);//合同开始日期
                }
                break;
                case "contractStatusValue": {//前端(目前状态列)
                    order.append("t.contract_status ").append(sortOrder);//合同状态
                }
                break;
                case "orderStatusValue": {//前端(目前状态列)
                    order.append("o.order_status ").append(sortOrder);//订单状态
                }
                break;
                case "reviewName": {//前端(审核人列)
                    order.append("ua.user_name ").append(sortOrder);//审核人
                }
                break;
                default:
                    break;
            }
        }
        List<ContractAndOrderVO> contractAndOrderVOList = null;
        if(!StringUtils.isBlank(queryType)){
            if("contract".equals(queryType)){//查询合同列表
                contractAndOrderVOList = contractAndOrderDbService.selectContractVOList(customerId,order.toString());
            }else if("order".equals(queryType)){//查询订单列表
                contractAndOrderVOList = contractAndOrderDbService.selectOrderVOList(customerId,order.toString());
            }
        }
        PageInfo<ContractAndOrderVO> pageInfo = new PageInfo<ContractAndOrderVO>(contractAndOrderVOList);
        return new DhPageInfo<ContractAndOrderVO>(pageInfo, contractAndOrderVOList);
    }

    /**
     * (客服部)合同&订单-》合同查看-》编辑详情
     * @param contractId  合同ID
     * @author yincuimei
     * @return
     */
    public ContractDetailVO selectContractDetailVOById(String contractId){
        if(!StringUtils.isBlank(contractId)){
            return customerContractDbService.selectContractDetailVOById(contractId);
        }
        return null;
    }

    /**
     * 合同列表-》查看-》合同编辑
     * @param customerContractUpdateQO
     * @author yincuimei
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean updateCustomerContract(CustomerContractUpdateQO customerContractUpdateQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        String accountId = userAccount.getAccountId();//当前登录人账号ID
        String userName = userAccount.getUserName();//登录人姓名
        Boolean result = false;
        if(customerContractUpdateQO != null){
            Short logType = WorkLogEnum.LOG_TYPE_CONTRACT.getCode().shortValue();//日志类型
            String contractId = customerContractUpdateQO.getContractId();//合同主键
            String orderId = customerContractUpdateQO.getOrderId();//订单主键
            String customerId = customerContractUpdateQO.getCustomerId();//客户ID
            Date contractStartDate = customerContractUpdateQO.getContractStartDate();//合同开始日期
            Date contractEndDate = customerContractUpdateQO.getContractEndDate();//合同结束日期
            String logRemark = customerContractUpdateQO.getRemark() + "  " + userName;//备注
            if(!StringUtils.isBlank(contractId)){
                //1:从数据库查出当前合同信息
                ContractDetailVO contractDetailVO = customerContractDbService.selectContractDetailVOById(contractId);
                String contractNumber = contractDetailVO.getContractNumber();
                if(contractDetailVO != null){
                    CustomerContract customerContract = new CustomerContract(); //合同
                    CustomerProductOrder customerProductOrder = new CustomerProductOrder();//订单
                    List<CustomerServiceWorkLog> workLogList = new ArrayList<CustomerServiceWorkLog>();//日志
                    String contractType = contractDetailVO.getContractType();
                    String contractTypeNew = customerContractUpdateQO.getContractType();
                    if(!contractTypeNew.equals(contractType)){//合同类型
                        customerContract.setContractType(contractTypeNew);
                        customerProductOrder.setContractType(contractTypeNew);
                        String logContent = getLogContent(userName,"将【"+contractNumber+ "】的合同类型:\"", CustomerContractEnum.getMessage(contractType),CustomerContractEnum.getMessage(contractTypeNew));
                        CustomerServiceWorkLog customerServiceWorkLog = workLogService.getCustomerServiceWorkLog(accountId,customerId,logType,logContent,logRemark);
                        workLogList.add(customerServiceWorkLog);
                    }
                    String contractStatusText = contractDetailVO.getContractStatusText() == null ? "":contractDetailVO.getContractStatusText();
                    String contractStatusTextNew = customerContractUpdateQO.getContractStatusText() == null ? "" : customerContractUpdateQO.getContractStatusText();
                    if(!contractStatusText.equals(contractStatusTextNew)){
                        if(!StringUtils.isBlank(contractStatusText) || !StringUtils.isBlank(contractStatusTextNew)){//合同状态
                            customerContract.setContractStatus(customerContractUpdateQO.getContractStatus());
                            String logContent = getLogContent(userName,"将【"+contractNumber+ "】的合同状态:\"",contractStatusText,contractStatusTextNew);
                            CustomerServiceWorkLog customerServiceWorkLog = workLogService.getCustomerServiceWorkLog(accountId,customerId,logType,logContent,logRemark);
                            workLogList.add(customerServiceWorkLog);
                        }
                    }

                    if(!(customerContractUpdateQO.getContactName() != null ? customerContractUpdateQO.getContactName():"").equals(contractDetailVO.getContactName())){//客户联系人
                        if(!StringUtils.isBlank(customerContractUpdateQO.getContactName()) || !StringUtils.isBlank(contractDetailVO.getContactName())){
                            customerContract.setContactName(customerContractUpdateQO.getContactName());
                            customerProductOrder.setContactPerson(customerContractUpdateQO.getContactName());
                            String logContent = getLogContent(userName,"将【"+contractNumber+ "】的客户联系人:\"",contractDetailVO.getContactName(),customerContractUpdateQO.getContactName());
                            CustomerServiceWorkLog customerServiceWorkLog = workLogService.getCustomerServiceWorkLog(accountId,customerId,logType,logContent,logRemark);
                            workLogList.add(customerServiceWorkLog);
                        }
                    }
                    if(!(customerContractUpdateQO.getContactDetails() !=  null ? customerContractUpdateQO.getContactDetails():"").equals(contractDetailVO.getContactDetails())){//联系方式
                        if(!StringUtils.isBlank(customerContractUpdateQO.getContactDetails()) || !StringUtils.isBlank(contractDetailVO.getContactDetails())){
                            customerContract.setContactDetails(customerContractUpdateQO.getContactDetails());
                            customerProductOrder.setBindMobilePhoneNumber(customerContractUpdateQO.getContactDetails());
                            String logContent = getLogContent(userName,"将【"+contractNumber+ "】的联系方式:\"",contractDetailVO.getContactDetails(),customerContractUpdateQO.getContactDetails());
                            CustomerServiceWorkLog customerServiceWorkLog = workLogService.getCustomerServiceWorkLog(accountId,customerId,logType,logContent,logRemark);
                            workLogList.add(customerServiceWorkLog);
                        }
                    }
                    if(!(customerContractUpdateQO.getCustomerEmail() != null ? customerContractUpdateQO.getCustomerEmail():"").equals(contractDetailVO.getCustomerEmail())){//客户邮箱
                        if(!StringUtils.isBlank(customerContractUpdateQO.getCustomerEmail()) || !StringUtils.isBlank(contractDetailVO.getCustomerEmail())){
                            customerContract.setCustomerEmail(customerContractUpdateQO.getCustomerEmail());
                            customerProductOrder.setCustomerEmail(customerContractUpdateQO.getCustomerEmail());
                            String logContent = getLogContent(userName,"将【"+contractNumber+ "】的客户邮箱:\"",contractDetailVO.getCustomerEmail(),customerContractUpdateQO.getCustomerEmail());
                            CustomerServiceWorkLog customerServiceWorkLog = workLogService.getCustomerServiceWorkLog(accountId,customerId,logType,logContent,logRemark);
                            workLogList.add(customerServiceWorkLog);
                        }
                    }

                    if(contractStartDate != null && contractEndDate != null) {//合同起止日期
                        if (contractStartDate != contractDetailVO.getContractStartDate() ||
                                contractEndDate != contractDetailVO.getContractEndDate()) {
                            String contractStartDateStr = "";
                            String contractEndDateStr = "";
                            String oldValue = "";
                            String newValue = "";
                            if (contractDetailVO.getContractStartDate() != null) {
                                contractStartDateStr = DateUtil.formatDate(contractDetailVO.getContractStartDate(), "yyyy-MM-dd");
                                oldValue += contractStartDateStr;
                            }
                            if (contractDetailVO.getContractEndDate() != null) {
                                contractEndDateStr = DateUtil.formatDate(contractDetailVO.getContractEndDate(), "yyyy-MM-dd");
                                if (!StringUtils.isBlank(oldValue)) {
                                    oldValue += "至" + contractEndDateStr;
                                } else {
                                    oldValue += contractEndDateStr;
                                }
                            }

                            newValue += DateUtil.formatDate(contractStartDate, "yyyy-MM-dd");
                            newValue += "至" + DateUtil.formatDate(contractEndDate, "yyyy-MM-dd");
                            if (!oldValue.equals(newValue)) {
                                String logContent = getLogContent(userName, "将【" + contractNumber + "】的合同起止日期:\"", oldValue, newValue);
                                CustomerServiceWorkLog customerServiceWorkLog = workLogService.getCustomerServiceWorkLog(accountId, customerId, logType, logContent, logRemark);
                                workLogList.add(customerServiceWorkLog);
                            }

                            Date membershipStartTm = null;
                            Date membershipExpirationTm = null;
                            String type = customerContractUpdateQO.getContractType();
                            //2: 修改客户(合同状态为生效中的和客户表的会员起止时间作对比)
                            if ("2".equals(customerContractUpdateQO.getContractStatus())) {//生效中的合同
                                if ("2".equals(type) || "4".equals(type) || "7".equals(type)) {//会员合同
                                    if (!StringUtils.isBlank(customerId)) {
                                        //2-1.从数据库查出当前客户信息
                                        CustomerDetailVO customerDetailVO = customerDbService.selectCustomerDetailVO(customerId);
                                        if (customerDetailVO != null) {
                                            Customer customer = new Customer();
                                            customer.setCustomerId(customerId);//客户主键
                                            customer.setUpdatePeopleId(accountId);//更新人ID
                                            customer.setUpdateTm(new Date());//更新时间
                                            membershipStartTm = customerDetailVO.getMembershipStartTm();
                                            membershipExpirationTm = customerDetailVO.getMembershipExpirationTm();
                                            if (membershipStartTm != null) {
                                                if (contractStartDate.before(membershipStartTm)) {
                                                    membershipStartTm = contractStartDate;
                                                    customer.setMembershipStartTm(membershipStartTm);
                                                }
                                            }
                                            if (membershipExpirationTm != null) {
                                                if (contractEndDate.after(membershipExpirationTm)) {
                                                    membershipExpirationTm = contractEndDate;
                                                    customer.setMembershipExpirationTm(membershipExpirationTm);
                                                }
                                            }
                                            if (customerDetailVO.getMembershipLevel() == null || customerDetailVO.getMembershipLevel() == 0) {//客户类型为非会员客户的
                                                customer.setMembershipLevel(1);//将客户置为会员客户
                                            }
                                            //2-2. 修改客户表
                                            customerDbService.updateCustomerByCustomerId(customer);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //3: 修改回款表合同类型(合同状态为生效中，合同类型为会员新单合同或会员续费合同的)
                    if ("2".equals(customerContractUpdateQO.getContractStatus())) {
                        if (!StringUtils.isBlank(contractTypeNew)) {
                            //合同状态为生效中，合同类型为【会员新单合同、会员续费合同的修改回款表合同类型】
                            if ("2".equals(contractTypeNew) || "4".equals(contractTypeNew)) {
                                ReturnMoney returnMoney = new ReturnMoney();
                                returnMoney.setContractId(contractId);
                                returnMoney.setUpdateTm(new Date());
                                returnMoney.setUpdateBy(accountId);
                                returnMoney.setContractType(contractTypeNew);
                                returnMoneyDbservice.updateReturnMoneyByContractId(returnMoney);
                            }
                        }
                    }

                    //4: 修改合同
                    customerContract.setContractId(customerContractUpdateQO.getContractId());
                    customerContract.setContractStartDate(customerContractUpdateQO.getContractStartDate());
                    customerContract.setContractEndDate(customerContractUpdateQO.getContractEndDate());
                    customerContract.setUpdatePeopleId(accountId);
                    customerContract.setUpdateTm(new Date());
                    result = customerContractDbService.updateCustomerContract(customerContract);

                    //5: 修改订单
                    if(!StringUtils.isBlank(orderId)){
                        customerProductOrder.setProductOrderId(orderId);
                        customerProductOrder.setUpdatePeopleId(accountId);
                        customerProductOrder.setUpdateTm(new Date());
                        result = customerProductOrderDbService.updateProductOrder(customerProductOrder);
                    }

                    //6: 批量新增日志
                    if(workLogList != null && workLogList.size() > 0){//日志集合不为空执行批量插入
                        result = workLogService.insertWorkLogBatch(workLogList);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public Map addCustomerContract(String contractAnnexId,String customerId,String customerName,String contractStartDate,String contractEndDate,String contractReviewNotes)throws ParseException {
        HashMap<Object, Object> map = new HashMap<>();
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        Date start = format1.parse(contractStartDate);
        Date end = format1.parse(contractEndDate);
        long startDateTime = start.getTime();
        long endDateTime = end.getTime();
        //获取结束时间到开始时间的天数
        int time = (int) ((endDateTime - startDateTime) / (1000 * 3600 * 24)) + 1;

        //days相当于15个月的天数
        int days = 459;
        int day = 365;
        if (time >= days){
            map.put("code", 1);
            map.put("msg", "开始和结束时间不能超过15个月");
            return map;
        }
        if(time < day){
            map.put("code", 1);
            map.put("msg", "开始和结束时间不能小于一年");
            return map;
        }
        String guid = CommonUtils.getGUID();
        long timeInMillis = Calendar.getInstance().getTimeInMillis();
        String contractNumber = "Z"+timeInMillis;
        UserAccount user = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        CustomerContractVO customerContractVO = new CustomerContractVO();
        customerContractVO.setContractId(guid);
        customerContractVO.setContractNumber(contractNumber);
        customerContractVO.setReviewerId(user.getAccountId());
        customerContractVO.setReviewerName(user.getUserName());
        customerContractVO.setContractStatus("2");
        customerContractVO.setContractType("2");
        customerContractVO.setContractStartDate(start);
        customerContractVO.setContractEndDate(end);
        customerContractVO.setContractReviewNotes(contractReviewNotes);
        customerContractVO.setCustomerId(customerId);
        customerContractVO.setCustomerName(customerName);
        customerContractVO.setOldContract("2");
        customerContractVO.setDeleteStatus("0");
        customerContractVO.setCreatePeopleName(user.getAccountId());
        customerContractVO.setContractAnnexId(contractAnnexId);
        contractAndOrderDbService.addCustomerContract(customerContractVO);
        map.put("code", 0);
        map.put("msg", "成功");
        return map;
    }

    /**
     * 日志内容
     * @param userName  --操作人名
     * @param type      --操作内容类型
     * @param oldValue  --原值
     * @param newValue  --新值
     * @author yincuimei
     * @return
     */
    public String getLogContent(String userName,String type,String oldValue,String newValue){
        if(StringUtils.isBlank(oldValue) || "请选择".equals(oldValue)){
            oldValue = "空";
        }
        if(StringUtils.isBlank(newValue) || "请选择".equals(newValue)){
            newValue = "空";
        }
        return userName + type + oldValue + "\"改为\"" + newValue + "\"";
    }
}
